package com.wlsk.license.helper;


import feign.Request;
import feign.Response;
import feign.Util;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import static feign.Util.decodeOrDefault;

@Slf4j
public class FeignLogger extends feign.Logger {


    @Override
    protected void log(String configKey, String format, Object... args) {
    }

    @Override
    protected void logRequest(String configKey, Level logLevel, Request request) {
        Request.HttpMethod httpMethod = request.httpMethod();
        String url = request.url();
        String param = " ";

        if (request.body() != null) {
            param = new String(request.body(), Util.UTF_8);
        }
        log.info("{}---> method:{} url:{}, param:{}.", configKey, httpMethod, url, param);
    }

    @Override
    protected void logRetry(String configKey, Level logLevel) {
        log.info(configKey, "---> RETRYING");
    }

    @Override
    protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, long elapsedTime) throws IOException {
        String result = "";
        try {
            if (response.body() != null) {
                byte[] bodyData = Util.toByteArray(response.body().asInputStream());
                result = decodeOrDefault(bodyData, Util.UTF_8, "Binary data");
                return response.toBuilder().body(bodyData).build();
            }
            return response;
        } finally {
            if (response.status() == 200) {
                log.info("{}---> result:{}.", configKey, result);
            } else {
                log.error("{}---> result:{}.", configKey, result);
            }
        }
    }

    @Override
    protected IOException logIOException(String configKey, Level logLevel, IOException ioe, long elapsedTime) {
        log.info("{}<--- ERROR {}: {}", configKey, ioe.getClass().getSimpleName(), ioe.getMessage());
        StringWriter sw = new StringWriter();
        ioe.printStackTrace(new PrintWriter(sw));
        log.info("{}{}", configKey, sw);
        return ioe;
    }
}
